import { createRouter, createWebHashHistory } from 'vue-router'

import { usePermissionStore } from '@/stores/permission'
import { useTabStore } from '@/stores/tab'

import { staticRoutes } from './routes'

// 拥有判断是否 刷新了一次路由
let isAddRouter = false

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: staticRoutes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

// 动态添加路由的函数
const addRouter = async () => {
  const permissionStore = usePermissionStore()
  await permissionStore.init()
  permissionStore.routes.forEach((item) => {
    router.addRoute('Layout', item)
  })
  isAddRouter = true
}

// 全局前置守卫：处理登录状态、动态路由加载等
router.beforeEach(async (to, _, next) => {
  const isAuthenticated = Boolean(localStorage.getItem('token')) // 模拟登录状态

  // 如果是登录页面，直接跳转
  if (to.path === '/login') {
    isAddRouter = false
    return next()
  }

  // 未登录，跳转到登录页面
  if (!isAuthenticated) {
    return next({ path: '/login' })
  }

  // 是否加载新的路由
  if (!isAddRouter) {
    await addRouter()
    next({ ...to, replace: true })
    return
  }
  window.$loadingBar?.start()
  next()
})

// 全局后置钩子：处理页面标题及其他操作
router.afterEach((to) => {
  const { title } = to.meta
  if (title) {
    document.title = String(title)
  }

  if (to.path !== '/login') {
    const tabsStore = useTabStore()
    // 如果是首次打开该标签，则添加
    tabsStore.add({
      label: String(to.meta.i18nKey || to.name || ''),
      value: to.path,
    })
  }

  window.$loadingBar?.finish()
})

export { router }
